%% @author Administrator
%% @doc @todo Add description to fun_scene_nn.


-module(fun_scene_nn).
-include("common.hrl").
%% ====================================================================
%% API functions
%% ====================================================================
%%比牌的时候,花牌是真实字面值，计算牛牛的时候，花牌都是10

-export([start_game/1,join_game/1,init/1,update_admin/1,bet/1,req_open_card/1,
		 drop_all_bet/1,leave_room/1,get_status/0,
		 robot_bet/1,cal_open_card/0,game_over/0,set_bet/0,test_card/0,test_max/0]).

-record(vic_info,{type=0,vic=0,fail=0}).
-define(INIT_VIC,[#vic_info{type=1},#vic_info{type=2},#vic_info{type=3},#vic_info{type=4},#vic_info{type=5}]).

-define(ROBOT_BET,robot_bet(3)).
-define(INIT_ROBOT,init_robot_info()).


init(AdminInfo)->
	?debug("init========"),
	erlang:put(game_num, 0),
	erlang:put(vic_info,?INIT_VIC),
	erlang:put(admin, AdminInfo),
	init_admin(AdminInfo),
	erlang:put(usr, []),
	erlang:put(select_bet, []),
	erlang:put(multy_select_bet, []),
	start_game([]),
%% 	timer:apply_after(100, gen_server, cast, [self(), {process_pt,?MODULE,start_game,[]}]).
	ok.


leave_room({{},Uid,_Sid})->
	  Player=#player{coin=Coin}=erlang:get(Uid),
	  erlang:put(Uid,Player#player{leave=1,sid=0}),
	  CurrencyType=erlang:get(?CurrencyType),
	?debug("CurrencyType=~p",[CurrencyType]),
	case CurrencyType of
		2->
		   gen_server:cast({global, agent_mng},{leave_room_add_currenvy,Uid,Coin});
		3->gen_server:cast({global, agent_mng},{leave_room_add_integer,Uid,Coin,erlang:get(scene_id)});
		_-> gen_server:cast({global, agent_mng},{leave_room_add_coin,Uid,Coin})
	end,
	
	  update_usr_num().



%% @doc 开始游戏
start_game([])->
	?debug("start_game========"),
	fun_scene_open_card:start_game(),
	erlang:put(max_bet_info, []),
	FapaiTime=fun_scene_time:get_fapai_time(),
	Time=util:unixtime()+util:floor(FapaiTime/1000),
	set_game_status(util:unixtime(),fapai,Time),
	init_card(),
	cal_card(),
	?debug("FapaiTime=~p",[FapaiTime]),
	timer:apply_after(FapaiTime, gen_server, cast, [self(), {process_pt,?MODULE,set_bet}]),
	ok. 	


set_bet()->
	?debug("set_bet============="),
	KaiShiXiaZhuTime=fun_scene_time:get_kaishixiazhu_texiao_time(),
	XiaZhuTime=fun_scene_time:get_xiazhu_time(),
	Time=util:unixtime()+util:floor((KaiShiXiaZhuTime+XiaZhuTime)/1000),
	set_game_status(util:unixtime(),xiazhu,Time),
	AdminInfo=erlang:get(admin),
	case lists:keyfind(?SceneCurrency, 1, AdminInfo) of
	{?SceneCurrency,?Coin}->
			?INIT_ROBOT,
			?ROBOT_BET;
		_->
			XiaZhuTime=fun_scene_time:get_xiazhu_time(),
			TingzhiXIazhuTime=fun_scene_time:get_tingzhixiazhu_time(),
			?debug("XiaZhuTime=~p,TingzhiXIazhuTime=~p",[XiaZhuTime,TingzhiXIazhuTime]),
			timer:apply_after(XiaZhuTime+TingzhiXIazhuTime, gen_server, cast, [self(), {process_pt,?MODULE,cal_open_card}])
	end.


robot_bet(Num)->
	if
	Num>0->
		XiaZhuTime=fun_scene_time:get_xiazhu_time(),
		PerTime=util:floor(XiaZhuTime/3),
		timer:apply_after(PerTime, gen_server, cast, [self(), {process_pt,?MODULE,robot_bet,Num-1}]);
	true->
		TingzhiXIazhuTime=fun_scene_time:get_tingzhixiazhu_time(),
	  timer:apply_after(TingzhiXIazhuTime, gen_server, cast, [self(), {process_pt,?MODULE,cal_open_card}])
	end.




%% @doc  计算卡牌开牌顺序
cal_open_card()->
	PlayerInfo=get_player_data(),
	F=fun(#player{id=Uid,select=Select,multy_select=Multy_select},{L1,L2,L3,L4})->
			  Bet1=cal_single_player_bet(1, Select)+cal_single_player_bet(1, Multy_select),
			  Bet2=cal_single_player_bet(2, Select)+cal_single_player_bet(2, Multy_select),
			  Bet3=cal_single_player_bet(3, Select)+cal_single_player_bet(3, Multy_select),
			  Bet4=cal_single_player_bet(4, Select)+cal_single_player_bet(4, Multy_select),
			 { L1++[{Uid,Bet1}],L2++[{Uid,Bet2}],L3++[{Uid,Bet3}],L4++[{Uid,Bet4}]} end,
	{BetList1,BetList2,BetList3,BetList4}=lists:foldl(F, {[],[],[],[]}, PlayerInfo),
	 Bets1=sort_bet(BetList1),
 	Bets2=sort_bet(BetList2),
 	Bets3=sort_bet(BetList3),
 	Bets4=sort_bet(BetList4),
	[{1,L1},{2,L2},{3,L3},{4,L4},{5,L5}]=erlang:get(card),
	{Uid,_,NextKey}=erlang:get(open_card_info),
	All_time=fun_scene_time:get_all_open_card_time(),
	Time=util:unixtime()+util:floor(All_time/1000),
		set_game_status(util:unixtime(),jiesuan,Time),
%% 	?debug("Uid=~p,open_card_info=~p",[Uid,{L1,L2,L3,L4,L5}]),
	erlang:put(open_card_info, {Uid,[{1,L1,Bets1},{2,L2,Bets2},{3,L3,Bets3},{4,L4,Bets4},{5,L5,[]}],NextKey}),
	timer:apply_after(100, gen_server, cast, [self(), {process_pt,fun_scene_open_card,
													   sys_open_card,{NextKey,5,fun_scene_open_card:get_game_num()}}]).


	

	
 req_open_card({{Type,Index,OpenType},Uid,_Sid})->
	?debug("req_open_card======"),
	 case get_status() of
		 3->
			 ?debug("req_open_card======"),
			 case erlang:get(open_card_info) of
				 {Uid,_Open_card,Type}->
					 ?debug("req_open_card====== Uid Type,Index=~p",[{Uid,Type,Index}]),
					 fun_scene_open_card:open_card({Type,Index,OpenType});
				 _->?debug("req_open_card fail===="),skip
			 end;
		 _->skip
	 end.
%% 当前这局游戏结束
game_over()->
	pack_game_over(),
	?debug("game over============="),
	IntervalTime=fun_scene_time:get_two_game_interval_time(),
	Time=util:unixtime()+util:floor(IntervalTime/1000),
	set_game_status(util:unixtime(),zhunbei,Time),
	timer:apply_after(IntervalTime, gen_server, cast, [self(), {process_pt,?MODULE,start_game,[]}]).
%% @doc 进入游戏
join_game({Uid,Sid,Name,HeadId,CardInfo,SceneCoinInfo})->	
          	join_game(Uid,Sid,Name,HeadId,CardInfo,SceneCoinInfo).
update_admin(AdminInfo)->		
		erlang:put(admin, AdminInfo).
%%@doc 下注
bet({{Bets,Type,Multiple},Uid,_Sid})->
	case erlang:get(masterId) of
		Uid->skip;
		_->
		case get_status() of 
			2->
				case lists:member(Bets, [100,500,1000,5000,10000]) of
					true->						
						UsrInfo=#player{coin=Coin,select=Seclet,multy_select=MultySelect}=erlang:get(Uid),
						
						case 	get_select(Type,Bets,Multiple,Seclet,MultySelect,Coin) of
							{true ,NewSelect,NewMultySelect}->
								NewUsrInfo= UsrInfo#player{coin=Coin-Bets,select=NewSelect,multy_select=NewMultySelect},						
								erlang:put(Uid, NewUsrInfo),
								update_max_bet(Uid, Type, NewSelect, NewMultySelect),
								{Allbet,AllmutyBet}=cal_select(Type),
								AddBet=case lists:keyfind(Type, 1, NewSelect) of
										   false->0;
										   {_,B1}->B1
									   end,
								AddMultyBet=case lists:keyfind(Type, 1, NewMultySelect) of
												false->0;
												{_,B2}->B2
											end,
								
								broad_cast(?PT_RES_NIUNIU_BETS, {Uid,Type,Bets,Coin-Bets,Multiple,Allbet,AllmutyBet,AddBet,AddMultyBet});
							_->skip
						end;
					_->skip
				end;
			_->skip
		end
	end.
get_status()->
	case erlang:get(?GAME_STATUS) of
		{fapai,_}->
			1;
		{xiazhu,_}->
			2;
		{jiesuan,_}->
			3;
		{zhunbei,_}->
			0
	end.
drop_all_bet({{},Uid,Sid})->
	case get_status() of
		2->
			Player=erlang:get(Uid),
			#player{multy_select=MultySelect,select=Select,coin=Coin}=Player,
			F=fun({_,Bet},N)->
					  N+Bet end,
			Coin1=lists:foldl(F, 0, MultySelect),
			Coin2=lists:foldl(F, 0, Select),
			NewPlayer=Player#player{coin=Coin+Coin1+Coin2,multy_select=[],select=[]},
			pt:send(Sid, ?PT_RES_DROP_ALL_BET, {1,Coin+Coin1+Coin2}),
			erlang:put(Uid, NewPlayer),
			drop_update_max_bet(Uid);
		_->pt:send(Sid, ?PT_RES_DROP_ALL_BET, {0,0})
	end.
	
test_card()->
List=[#card{col=3,value=1,index=1},#card{col=2,value=8,index=2},#card{col=3,value=9,index=3},#card{col=3,value=12,index=4},
 	#card{col=2,value=5,index=5}],
	cal_card_ex(List).
test_max()->
	List=[#card{col=1,value=2,index=5,open=0},#card{col=1,value=4,index=4,open=0},#card{col=3,value=1,index=3,open=0}
		 ,#card{col=4,value=12,index=2,open=0},#card{col=2,value=2,index=1,open=0}],
	get_max_card(List).
test_bin(Bin)->
	{Cmd,_R}=pt:read_short(Bin),
	?debug("Cmd=~p",[Bin]),
	
	ok.

sort_bet([])->[]	;
sort_bet(List)->	
	F_sort=fun({_,Bet1},{_,Bet2})->
				   Bet1>=Bet2 end,
	lists:sort(F_sort, List).
init_card(0,L)->L;
init_card(Num,L)->
	F=fun(N,List)->
			  List++[{#card{col=Num,value=N},1}] 
	  end,
	Col1=lists:foldl(F, [], ?CardValueList), 
	init_card(Num-1,L++Col1). 

get_max_card(List)->
		F=fun(#card{col=Col1,value=Value1},#card{col=Col2,value=Value2})->
				  if
					  Value1>Value2->true;
					  true->
						  if
							  Col1>Col2->true;
							  true->false
						  end
				  end
		  end,
		[Card|_]=lists:sort(F, List),
		Card.	
cal_bet(_CardList,_Value,[],_IsMulty,AllBet)->AllBet;
cal_bet(CardList,Value,[{SelectType,Bet}|Next],IsMulty,AllBet)->
	{5,{Num,_}}=lists:keyfind(5, 1, Value),
	{SelectType,{N,_}}=lists:keyfind(SelectType, 1, Value),
	MaxMuty1=get_multy(N),
	MaxMuty2=get_multy(Num),
	Multy=
		if
			IsMulty==0->1;
			true->if
					  	MaxMuty1> MaxMuty2->MaxMuty1;
						true->MaxMuty2
			end
		end,
	AddBet=
			if
				N>Num->Bet+Bet*Multy;
				N==Num->
								{_,CardList1}=lists:keyfind(5, 1, CardList),
								{_,CardList2}=lists:keyfind(SelectType, 1, CardList),
								#card{col=Col1,value=Value1}=get_max_card(CardList1),
								#card{col=Col2,value=Value2}=get_max_card(CardList2),
								if
									Value1>Value2->Bet+Bet*Multy;
									true->
										if
											Col1>	Col2->Bet+Bet*Multy;
											true->-1*(Multy-1)*Bet
										end
								end;
				true->-1*(Multy-1)*Bet
			end,
	NewBet=AllBet+AddBet,
	cal_bet(CardList,Value,Next,IsMulty,NewBet).
get_multy(Num)->
	if
		Num>=10->3;
		true->2
	end.
get_vic_info(Type)->
	CardList=erlang:get(card),
	ValueInfo=erlang:get(value),
	{Type,{V1,_}}=lists:keyfind(Type, 1, ValueInfo),
  	{5,{V5,_}}=lists:keyfind(5, 1, ValueInfo),
	if
		V1>V5->1;
		V1==V5->check_card_list(Type,CardList);
		true->0
	end.

check_card_list(Type,CardList)->
	{Type,L1}=lists:keyfind(Type, 1, CardList),
	{5,L5}=lists:keyfind(5, 1, CardList),
	#card{col=C1,value=V1}=get_max_card(L1),
	#card{col=C5,value=V5}=get_max_card(L5),
	if
		V1>V5->1;
		V1==V5->if
				  C1>C5->1;
				  true->0
			  end;
		true->0
	end.
pack_game_over()->
	CardList=erlang:get(card),
	ValueList=erlang:get(value),
	Usrs=erlang:get(usr),
	VicRecordList=get(vic_info),
	F1=fun({Key,{Num,L}},{RetVicRecordList,RetL})->
			  F2=fun(#card{index=Index} )->
						Index  end,
				RL=lists:map(F2, L),
			  IndexInfo=case RL of
							[]->{0,0};
							_->list_to_tuple(RL)
						end,
			  CurrenyVic=get_vic_info(Key),
			  VicInfo=lists:keyfind(Key, #vic_info.type, RetVicRecordList),
			  FailNum=VicInfo#vic_info.fail,
	   		  VicNum=VicInfo#vic_info.vic,
			  {Vic,Fail}=if
					   CurrenyVic==1->{FailNum,VicNum+1};
					   true->{FailNum+1,VicNum}
				   end,
			  NewVicInfo=VicInfo#vic_info{fail=Fail,vic=Vic},
			  NewRetVicRecordList=lists:keyreplace(Key, #vic_info.type, RetVicRecordList, NewVicInfo),
			{NewRetVicRecordList,RetL++[{Key,Num,IndexInfo,Fail,Vic,CurrenyVic}]} end,
	{NewVIcREcored,VueEndInfo}=lists:foldl(F1, {VicRecordList,[]},ValueList),
	erlang:put(vic_info, NewVIcREcored),
 	F=fun(Uid)->
			  Player=#player{ai=AI,id=Uid,card_info=CardInfo,sid=Sid,select=Select,multy_select=MultySelect,old_coin=Old,coin =Coin}=erlang:get(Uid),
			  Bet1=cal_bet(CardList, ValueList, Select, 0, 0),
			  Bet2=cal_bet(CardList, ValueList, MultySelect, 1, 0),
			  NewCoin=Bet1+Bet2+Coin,
			  AllBet=cal_bet(Select++MultySelect,0),
			  UpdateCoin=Old-NewCoin,
			  ?debug("UpdateCoin=~p,AllBet=~p",[UpdateCoin,AllBet]),
			  cal_platform(Uid,UpdateCoin,CardInfo,AllBet),
			  NewPlayer=Player#player{coin=NewCoin,select=[],old_coin=NewCoin,multy_select=[],sid=Sid},
			  if
				  AI == false andalso
				  Sid ==0 ->
					  delete_usr(Uid);
				  true->
			  erlang:put(Uid, NewPlayer)
			  end,
			  VicNum=-UpdateCoin,
			  ?debug("VicNum=~p",[VicNum]),
			  Vic=if
					  VicNum=<0->0;
					  true->1
				  end,			  
		case erlang:is_pid(Sid) of
			true->
			MasterBet=erlang:get(masterBets),
			pt:send(Sid, ?PT_RES_NIUNIU_GAME_OVER, {VueEndInfo,trunc(MasterBet*100),NewCoin,Vic,VicNum});
			_->skip
		end end,
	lists:foreach(F, Usrs).
cal_bet([],Add)->Add;
cal_bet([{_,Bet}|Next],Add)->
		cal_bet(Next,Bet+Add).


cal_platform(Uid,UpdateCoin,CardInfo,AllBet)->
	?debug("cal_platform=======UpdateCoin=~p,AllBet=~p",[UpdateCoin,AllBet]),
	CurrencyType=erlang:get(?CurrencyType),
	?debug("CurrencyType=~p",[CurrencyType]),
	case CurrencyType of
		2->
			?debug("UpdateCoin=~p",[UpdateCoin]),
			update_master_coin(UpdateCoin,Uid,CardInfo),
			update_club_leader_currency(Uid, CardInfo, AllBet);
		3->update_master_coin(UpdateCoin,Uid,CardInfo);
		_->?debug("11111111"),skip
	end.

update_club_leader_currency(Uid,#club_card_info{club_card_id=CardId,
								rebate=Rebate},Bet)->
	?debug("Rebate=~p,Bet=~p",[Rebate,Bet]),
	if
		Bet==0 orelse Rebate==0 ->skip;
		true->
			MasterBet=erlang:get(masterBets),
			End=((MasterBet)*1000-(Bet*Rebate))/1000,
			erlang:put(masterBets, End),
			?debug("update_club_leader_currency Bet=~p",[Bet]),
			gen_server:cast({global, agent_mng},{update_club_leader_currency_by_card,Uid,CardId,Bet,trunc(Bet*Rebate)/1000})
	end.
update_master_coin(0,_,_)->skip;
update_master_coin(UpdateCoin,Uid,CardInfo=#club_card_info{	club_card_id=CardId,
														   club_user_bear=Club_user_bear,
														   platform_bear=Platform_bear,
														   benefits=Benefits})->
	case erlang:get(?CurrencyType) of
		2->
			 ?debug("11111111"),
			ClubUpdate=trunc((UpdateCoin*Club_user_bear)/100),
			PlaformUpdate=trunc((UpdateCoin*Platform_bear)/100),
			?debug("update_master_coin,ClubUpdate=~p,PlaformUpdate=~p",[ClubUpdate,PlaformUpdate]),
			if
				Benefits==0->skip;
				true->					
					if				  
						UpdateCoin>0->				
							MasterBet=erlang:get(masterBets),
							End=MasterBet+PlaformUpdate,
							erlang:put(masterBets, End),
						gen_server:cast({global, agent_mng},{update_club_leader_currency_by_benifit,Uid,CardId,-UpdateCoin,ClubUpdate}),
							CardInfo#club_card_info{
													club_user_bear=Club_user_bear,
													platform_bear=Platform_bear,
													benefits=Benefits+ClubUpdate};
						UpdateCoin==0->CardInfo;
						true->
							if
								Benefits> ClubUpdate->
									MasterBet=erlang:get(masterBets),
									End=MasterBet+PlaformUpdate,
									erlang:put(masterBets, End),
									gen_server:cast({global, agent_mng},{update_club_leader_currency_by_benifit,Uid,CardId,util:abs(UpdateCoin),ClubUpdate}),
									CardInfo#club_card_info{
															club_user_bear=Club_user_bear,
															platform_bear=Platform_bear,
															benefits=Benefits+PlaformUpdate};	
								true->	
									MasterBet=erlang:get(masterBets),
									End=MasterBet+PlaformUpdate+Benefits+ClubUpdate,
									erlang:put(masterBets, End),
									gen_server:cast({global, agent_mng},{update_club_leader_currency_by_benifit,Uid,CardId,util:abs(UpdateCoin),-Benefits}),
									CardInfo#club_card_info{
															club_user_bear=Club_user_bear,
															platform_bear=Platform_bear,
															benefits=0}
							end
					
					end		
			end;
		3->
			SceneId=erlang:get(scene_id),
			SceneType=erlang:get(scene_type),
			MasterBet=erlang:get(masterBets),
			End=MasterBet+UpdateCoin,
			erlang:put(masterBets, End),
			gen_server:cast({global, agent_mng},{update_club_leader_interger,Uid,SceneId,CardId,SceneType,-UpdateCoin,End});							
			
		_->skip
	end.
			
delete_usr(Uid)->
	?debug("==============delete_usr===================~p",[Uid]),
	Usrs=erlang:get(usr),
	Ret=lists:delete(Uid, Usrs),
	erlang:put(usr, Ret),
	erlang:erase(Uid).




add_usr({Uid,Sid,Name,HeadId,CardInfo,Coin,Currency,Interger,AI})->
	?debug("Coin=~p,Currency=~p,Interger=~p",[Coin,Currency,Interger]),
%% 	AdimnInfo=erlang:get(admin),
%% 	?debug("AdimnInfo=~p",[AdimnInfo]),
	CurrencyType=erlang:get(?CurrencyType),
	UsrList=erlang:get(usr),
	?debug("CurrencyType=~p",[CurrencyType]),
	Need=case CurrencyType of
			 1->Coin;
			 2->Currency;
			 3->Interger;
		 	_->Coin
		 end,
	?debug("Need=~p",[Need]),
	case lists:member(Uid, UsrList) of
		false-> 
			erlang:put(usr, [Uid|UsrList]),
			erlang:put(Uid, #player{ai=AI,card_info=CardInfo,sid=Sid,id=Uid,head_id=HeadId,name=Name,old_coin=trunc(Need),coin=trunc(Need)});
		_->
			erlang:put(Uid, #player{ai=AI,sid=Sid,card_info=CardInfo,id=Uid,head_id=HeadId,name=Name,old_coin=trunc(Need),coin=trunc(Need)})
	end.

 

get_card(List,0,L)->{List,L};
get_card(List,Num,L)->
		{Card,Rest}=util:random_by_weight_ex(List),
		get_card(Rest,Num-1,L++[Card#card{index=Num}]).


%% @doc 进入游戏
join_game(Uid,Sid,Name,HeadId,CardInfo,#scene_coin{coin=Coin,currency=Currency,interger=Interger})->	
	?debug("Join Game Uid=~p,CardInfo=~p",[Uid,CardInfo]),
	add_usr({Uid,Sid,Name,HeadId,CardInfo,Coin,Currency,Interger,false}),
	gen_server:cast(Sid,{set_val, scene_pid, self()}),
	UsrList=get_player_data(),
	MasterId=erlang:get(masterId),
	MasterHead=erlang:get(masterHead),
	MasterName=erlang:get(masterName),
	MasterBets=erlang:get(masterBets),
	{SelectBets,MultySelectBets}=cal_join_bet_info(),
	{_,CardList,_}=erlang:get(open_card_info),
	F=fun({Type,CardTailList,_})->
			  F1=fun(#card{open=Open})->
						 Open==1 end,
			  NeedInfo=lists:filter(F1, CardTailList),
	  		{Type,NeedInfo}
	  end,
	CardInfoList=lists:map(F, CardList),
	{_,Time}=erlang:get(?GAME_STATUS),
	Status=get_status(),
	Now=util:unixtime(),
	Timestemp=if
				  Time>Now->Time-Now;
				  true->0
			  end,
	CurrencyType=erlang:get(?CurrencyType),
	NeedCoin=case CurrencyType of
				 1->Coin;
				 2->Currency;
				 3->Interger;
				 _->Coin
			 end,
	?debug("NeedCoin=~p",[NeedCoin]),
	RoomInfoBin=pt:pack_room_info(UsrList, MasterId, MasterHead, MasterName, 
								  trunc(MasterBets*100), SelectBets, MultySelectBets,Status, CardInfoList,Timestemp,CurrencyType,trunc(NeedCoin)),
	?debug("RoomInfoBin=~p",[RoomInfoBin]),
	pt:send(Sid, ?PT_RES_NIUNIU_ROOM_INFO, {RoomInfoBin}),
	test_bin(RoomInfoBin),
	update_usr_num().

cal_join_bet_info()->
	F=fun(Type,{L1,L2})->
		{L3,L4}=cal_select(Type),
		{L1++[{Type,L3}],	L2++[{Type,L4}]} end,
	lists:foldl(F, {[],[]}, [1,2,3,4]).


 


get_select(Type,Bets,Multiple,Seclet,MultySelect,Coin)->
	{ExitMultyBet,NewMultySelect}=
				case lists:keyfind(Type, 1, MultySelect) of
					false->{0,lists:keystore(Type, 1, MultySelect, {Type,Bets})};
					{Type,Old}->{Old,lists:keyreplace(Type, 1, MultySelect,  {Type,Bets+Old})}
				end,
	{ExitBet,NewSelect}=
		case lists:keyfind(Type, 1, Seclet) of
			false->{0,lists:keystore(Type, 1, Seclet, {Type,Bets})};
			{Type,OldBet}->{OldBet,lists:keyreplace(Type, 1, Seclet, {Type,Bets+OldBet})}
		end,
	case Multiple of
		1->
			if
				Coin>=Bets*3+ExitBet+ExitMultyBet*3->
					{true,Seclet,NewMultySelect};
				true->false
			end;
		_->
			if
				
				Coin>=Bets+ExitBet+ExitMultyBet*3->
					{true,NewSelect,MultySelect};
				true->
					false
			end
end.
				

cal_select(Type)->
	UidList=erlang:get(usr),
	case UidList of
		[]->{0,0};
		_->
			F=fun(Uid,{Num1,Num2})->
					  #player{select=Select,multy_select=MultySelect}=erlang:get(Uid),
					  Bet1=
						  case lists:keyfind(Type, 1, Select) of
							  false->0;
							  {_,B1}->B1
						  end,
					  Bet2=
						  case lists:keyfind(Type, 1, MultySelect) of
							  false->0;
							  {_,B2}->B2
						  end,
					  {Num1+Bet1,Num2+Bet2} end,
			lists:foldl(F, {0,0}, UidList)
	end.
	

cal_max_bet(Type,Seclet,MultySelect)->
	Bet1=
	case lists:keyfind(Type, 1, Seclet) of
		{Type,B1}->B1;
		_->0
	end,
		Bet2=
	case lists:keyfind(Type, 1, MultySelect) of
		{Type,B2}->B2*3;
		_->0
	end,
	Bet1+Bet2.
update_max_bet(Uid,Type,Seclet,MultySelect)->
	All_bet=cal_max_bet(Type,Seclet,MultySelect),
	MaxBetInfo=erlang:get(max_bet_info),
	case lists:keyfind(Type, 2, MaxBetInfo) of
		{_,_,OldBet}->
			if
				All_bet>OldBet->							
								?debug("Type=~p,All_bet=~p",[Type,All_bet]),
								erlang:put(max_bet_info, lists:keyreplace(Type, 2, MaxBetInfo, {Uid,Type,All_bet})),
								broad_cast(?PT_NOTYFY_MAX_BET, {Uid,Type,All_bet});
				true->skip
			end;
		_->
				?debug("Type=~p,All_bet=~p",[Type,All_bet]),
			erlang:put(max_bet_info, lists:keystore(Type, 2, MaxBetInfo, {Uid,Type,All_bet})),
			broad_cast(?PT_NOTYFY_MAX_BET, {Uid,Type,All_bet})						 
	end.
get_update_max_bet(UidList,Type)->
		F=fun(Uid)->
				  #player{select=Select,multy_select=MultySelect}=erlang:get(Uid),
					All_bet=cal_max_bet(Type,Select,MultySelect),
					{Uid,All_bet} end,
		Ret=lists:map(F, UidList),
		F1=fun({_,Bet1},{_,Bet2})->
			if
				Bet1>=Bet2->true;
				true->false
			end end,
		[{FUid,Fbet}|_]=lists:sort(F1, Ret),
		{FUid,Type,Fbet}.
			 

drop_update_max_bet(Uid)->
	UidList=erlang:get(usr),
	MaxBetInfo=erlang:get(max_bet_info),
	F=fun({MyUid,Type,_Allbet})->
			  if
				  MyUid==Uid->
										{NewUid,Type,NewBet}=get_update_max_bet(UidList,Type),
										erlang:put(max_bet_info, lists:keystore(Type, 2, MaxBetInfo, {NewUid,Type,NewBet})),
%% 										?debug("NewBet=~p",[NewBet]),
										broad_cast(?PT_NOTYFY_MAX_BET, 	{NewUid,Type,NewBet});	
			  	 true->skip
			end end,
	lists:foreach(F, MaxBetInfo).

				


%% @doc 初始化牌
init_card()->	
	 L=init_card(4, []),
	{R1,L1}=get_card(L, 5, []),
	{R2,L2}=get_card(R1, 5, []),
	{R3,L3}=get_card(R2, 5, []),
	{R4,L4}=get_card(R3, 5, []),
	{_,L5}   =get_card(R4, 5, []),
	CardList=[{1,L1},{2,L2},{3,L3},{4,L4},{5,L5}],
	erlang:put(card,CardList).

	
cal_card_ex(List)->
	cal_card_value(List).
%% @doc 计算牌型和值
cal_card()->
	List=erlang:get(card),
	Value=[{Key,cal_card_value(L1)}||{Key,L1}<-List],

	erlang:put(value, Value).


%% @doc 计算牛牛的字面值
cal_card_value(List)-> 
%% 	?debug("List=~p",[List]),
	L=permutation(3, List),
	RemList=cal_card_value(L,[]),
   {Max,_,MaxRest}=cal_rem_card_value(List,RemList,{0,[],[]}),
	{Max,MaxRest}.

cal_rem_card_value(_List,[],{Max,MaxList,MaxRest})->{Max,MaxList,MaxRest};
cal_rem_card_value(List,[RemList|Next],{Max,MaxList,MaxRest})->
	F=fun(Card,L)->
%% 			  ?debug("Card=~p,L=~p",[Card,L]),
			  lists:delete(Card, L) end,
	Rest=lists:foldl(F, List, RemList),
	Fsum=fun(#card{value=V},Num)->
				 if
					 V>10->Num+10;
					 true->Num+V
				 end
		 end,
	MaxNiu=lists:foldl(Fsum, 0, Rest),
%% 	?debug("MaxNiu=~p")
	case MaxNiu rem 10 of
		0->case check_max(Rest, MaxRest) of
							Rest->cal_rem_card_value(List,Next,{10,RemList,Rest});
							_->cal_rem_card_value(List,Next,{Max,MaxList,MaxRest})
				end;
		Other->					
			if
				Other>Max->cal_rem_card_value(List,Next,{Other,RemList,Rest});
				true->cal_rem_card_value(List,Next,{Max,MaxList,MaxRest})
			end
	end.
check_max(L1,[])->L1;
check_max([#card{col=C1,value=V1},#card{col=C2,value=V2}]=L1,[#card{col=C3,value=V3},#card{col=C4,value=V4}]=L2)->
	Max1=get_max_card(#card{col=C1,value=V1},#card{col=C2,value=V2}),
	Max2=get_max_card(#card{col=C3,value=V3},#card{col=C4,value=V4}),
	Max=get_max_card(Max1,Max2),
	case lists:member(Max, L1) of
		true->L1;
		_->L2
	end.


get_max_card(#card{col=C1,value=V1},#card{col=C2,value=V2})->
	if
		
			 V1>V2 -> #card{col=C1,value=V1};
			 V1==V2->if
						 			C1>C2->#card{col=C1,value=V1};
									true->#card{col=C2,value=V2}
								end;
			 true->#card{col=C2,value=V2}
	    end.
									
%%去掉重复的组合
check_merge(List,L)->
	F=fun(CardList)->
			  check_card_mege(CardList,List) end,
	lists:any(F, L).

check_card_mege(CardList,List)->
	F=fun(Card)->
			  lists:member(Card, CardList) end,
	lists:all(F, List) .

%%获取牛牛组合
cal_card_value([],L)->L;
cal_card_value([List|Next],L)->
	F=fun(#card{value=V},Old)->
			  if
				  V>10->10+Old;
				  true-> V+Old 
			  end
			  end,
	Num=lists:foldl(F, 0, List),
	case Num rem 10 of
		0->
			case check_merge(List,L) of
				false->
					cal_card_value(Next,L++[List]);
				_->cal_card_value(Next,L)
			end;
		_->cal_card_value(Next,L)
	end.


permutation(0, _) -> [[]];
permutation(_, []) -> [];
permutation(N, Xs) ->
    [ [X|Rs] || X <- Xs,
                Rs <- permutation(N-1, Xs--[X]) ].
	



	


get_player_data()->
		case erlang:get(usr) of
			UsrList when length(UsrList)>0->
				F=fun(Uid,L)->
							  Player=erlang:get(Uid),	
						  L++[Player] end,
				lists:foldl(F, [], UsrList);
			_->[]
		end.




%% @doc 初始化机器人
init_robot_info()->
	?debug("init_robot_info========="),
	Num=util:rand(10, 50),
	get_robot_info(Num).


get_robot_info(0)->ok;	
get_robot_info(Num)->
	ID=get_robot_id(),
	Head=rand:uniform(50),
	Name="机器人"++util:to_list(ID),
	Coin=1000000,
	add_usr({ID,0,Name,Head,0,Coin,0,0,true}),
	get_robot_info(Num-1).

get_robot_id()->
	case erlang:get(machineId) of
		?UNDEFINED->
			erlang:put(machineId, ?MachineId+1),
			?MachineId; 
		Num when erlang:is_integer(Num)->
			erlang:put(machineId, Num+1),
			Num
	end.


%% @doc设置游戏的状态
set_game_status(Now,Status,NextTime)->
	erlang:put(?GAME_STATUS, {Status,NextTime}),
	broad_cast(?PT_RES_GAME_STATUS, {get_status(),NextTime-Now}).


broad_cast(Cmd,Data)->
	UsrList=erlang:get(usr),
	F=fun(Uid)->
			case erlang:get(Uid) of
				#player{sid=Sid,ai=false,leave=0}->
							pt:send(Sid,Cmd,Data);
				_->skip
			end
	  	end,
	lists:foreach(F, UsrList).

init_admin(AdminInfo)->
	CurrencyType=proplists:get_value(?CurrencyType, AdminInfo),
	erlang:put(?CurrencyType, CurrencyType),
	case lists:keyfind(ptadmin, 1, AdminInfo) of
		{ptadmin,#admin_info{adminUid=Uid,current_admin_currency=Currency,adminName=Name,adminhead=Head}}->			
			erlang:put(masterName, Name),
			erlang:put(masterId, Uid),
			erlang:put(masterHead, Head),
			erlang:put(masterBets, Currency);
		_R->
			?debug("init_admin=~p",[_R]),
			erlang:put(masterId, 10000),		
			erlang:put(masterName, "小薇创想"),				
			erlang:put(masterHead, 10),				
			erlang:put(masterBets, 1000000)
		end.
cal_single_player_bet(Key,Select)->
	 case lists:keyfind(Key, 1, Select) of
		 false->0;
		 {Key,Num}->Num
	 end.
update_usr_num()->
	Usr=erlang:get(usr),
	F=fun(Uid)->
			  #player{leave=Leave}=erlang:get(Uid),
			   Leave==0 end,
	Need=lists:filter(F, Usr),
	Num=erlang:length(Need),
	broad_cast(?PT_RES_LEAVE_ROOM, {Num}).